package football

import (
	"go.uber.org/atomic"
	"longmen/server/config/global"
	football_behaviour2 "longmen/server/internal/services/nami/api/v5/sports/football/football_behaviour"
	"longmen/server/internal/services/nami/config"
	football2 "longmen/server/internal/services/nami/services/sports/football"
	"longmen/server/internal/services/nami/services/sports/football/fbcache"
	"longmen/server/internal/services/nami/utils"
	"longmen/server/internal/services/nami/utils/ratelimit"
	"longmen/server/internal/services/nami/utils/restyclient"
	"longmen/server/pkg/db/mysql/models/models_sports"
)

// SyncOddsLive 获取实时指数数据
// 返回实时变动的赔率数据，无赔率变动的比赛不返回
// 只返回最近60秒变化的赔率数据，需要客户自身把变动数据记录下来
//
// 范围：初盘、即时盘、滚球盘
// 每家公司每种指数的第一个盘口，即为初盘；初盘到开球为即时盘；开球后为滚球盘
//
// 建议请求频次：3秒/次
func (f Football) SyncOddsLive() {
	resp := football_behaviour2.OddsLiveApiResponse{}
	queryStr := config.BuildParamsAndUserAndSecret()
	err := restyclient.GetUrlAndBindRecords(config.FBOddsLive+queryStr, &resp)
	if err != nil {
		global.Log.Error("获取更新列表失败: ", err)
		return
	}
	mysqlRecords, natsRecords := resp.Results.GetByOdds()
	if len(mysqlRecords) == 0 {
		return
	}
	if len(natsRecords) > 0 {
		err = fbcache.NewOddsRedis().AsyncPublishLiveOdds(natsRecords)
		if err != nil {
			global.Log.Error("nats 推送失败： ", err)
		}
	}

	shardingInsert := make(map[int][]models_sports.FootballOdds)
	for _, odd := range mysqlRecords {
		if _, ok := shardingInsert[odd.MatchId]; !ok {
			shardingInsert[odd.MatchId] = make([]models_sports.FootballOdds, 0)
		}
		shardingInsert[odd.MatchId] = append(shardingInsert[odd.MatchId], odd)
	}
	for matchId, footballOdds := range shardingInsert {
		football2.ShardingCreate(matchId, footballOdds, 100)
	}
}

// SyncOddsHistory 获取单场比赛指数数据
// 返回单场比赛所有指数公司的指数变化历史，从初盘到请求接口的时刻（根据‘指数更新数据’接口变动更新，作为补充使用）
//
// 范围：初盘、即时盘、滚球盘
// 每家公司每种指数的第一个盘口，即为初盘；初盘到开球为即时盘；开球后为滚球盘
//
// 请求次数：120次/min
//
// 说明：
// 指数变化数据都在实时指数接口获取，实时指数接口返回的是最近60s内的全量比赛的变动指数数据，需本地记录
// 若指数数据获取有缺失或未获取到，再通过单场比赛指数接口进行查缺补漏
var fbLastId atomic.Int32
var fbOddsHistoryLimit, _ = ratelimit.Init(60, 120, 120)

func (f Football) SyncOddsHistory() {
	startTime, endTime := utils.GetDayStart2End()
	lastId := int(fbLastId.Load())
	ids := football2.GetTimeBetweenMatchIds(startTime, endTime, lastId)
	if len(ids) == 0 {
		global.Log.Info("数据已刷新完成")
		fbLastId.Store(0)
		return
	}
	for i, id := range ids {
		if err := fbOddsHistoryLimit.Limiting(); err == nil {
			resp := football_behaviour2.OddsHistoryApiResponse{}
			queryStr := config.BuildParamsAndUserAndSecret(map[string]interface{}{
				"id": id,
			})
			err = restyclient.GetUrlAndBindRecords(config.FBOddsHistory+queryStr, &resp)
			if err != nil {
				global.Log.Error("获取更新列表失败: ", err)
				continue
			}
			football2.ShardingCreate(id, resp.Results.GetByOdds(id), 1000)
			fbLastId.Store(int32(ids[i]))
		}

	}
}
